package com.xgimi.locales.utils

import com.alibaba.excel.EasyExcelFactory
import com.alibaba.excel.context.AnalysisContext
import com.alibaba.excel.event.AnalysisEventListener
import com.alibaba.excel.read.metadata.ReadSheet
import com.alibaba.excel.write.handler.SheetWriteHandler
import com.alibaba.excel.write.metadata.WriteSheet
import com.alibaba.excel.write.metadata.WriteTable
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder
import com.google.gson.Gson
import com.xgimi.locales.bean.ExportConfig
import com.xgimi.locales.bean.InputConfig
import com.xgimi.locales.bean.RowBean
import java.io.File
import java.util.*


/**
 * excel解析
 * com.alibaba:easyexcel
 */
object ExcelUtil {

    /**
     * 获取excel 的 sheet tab
     */
    fun getSheetList(excelFile: File):MutableList<ReadSheet>? {
        if (!excelFile.exists()) {
            return null
        }
        val build = EasyExcelFactory.read(excelFile).build()
        val sheetList = build.excelExecutor().sheetList()
        build.finish()
        return sheetList
    }

    fun readRowsBySheetName(
        inputConfig: InputConfig,
        progress: (RowBean) -> Unit,
        error: (msg: String) -> Unit,
        complete: (List<RowBean>) -> Unit
    ) {
        println("=====readRowsBySheetName=====start")
        val file = File(inputConfig.excelPath)
        if (!file.exists()) {
            error("${inputConfig.excelPath} Excel文件不存在")
            return
        }

        val sheetIndex = inputConfig.selectSheet?.sheetIndex ?: -1
        if (sheetIndex < 0) {
            error("${inputConfig.excelPath} Excel文件 Sheet index $sheetIndex 错误！")
            return
        }

        // 读取excel表格 Sheet 的内容，一行一行的读取的.
        EasyExcelFactory.read(file, object : AnalysisEventListener<HashMap<Int, String>>() {
            private val datas = ArrayList<RowBean>()
            private var allHeads = mutableListOf<String>() // 存储 cexcel 表格 所有的语言(ar,cs,de,el,en-rGB...)

            override fun invoke(cellDataMap: HashMap<Int, String>?, context: AnalysisContext?) {
                // 读取head
//                println("readRowsBySheetName read index:${context?.readRowHolder()?.rowIndex}")
                if (context?.readRowHolder()?.rowIndex == 1) {
                    allHeads = cellDataMap!!.map { it.value }.toMutableList()
                    // 将excel表格中所有的语言保存起来
                    inputConfig.allLangs = cellDataMap.filter { it.value != Constant.XML_NAME_TITLE && it.value != Constant.ID_TITLE &&
                            it.value != "values" && Constant.FIELD_PROPERTY != it.value }.map {
//                            println("readRowsBySheetName filter  map allHeads ${it.value}")
                        it.value
                    }
                    Collections.sort(inputConfig.allLangs)
                    return
                }

                if (inputConfig.allLangs.isNullOrEmpty()) {
//                    error("未读取到head属性!")
                    println("未读取到head属性!")
                    return
                }

                // 读取excel 翻译内容，将 keyName(id)以及各种属性读取出来，再将一行中各种语言对应的翻译保存起来。
                // 比如 langs["en-rGB"] = "Auto Focus on Startup"
                if (!cellDataMap.isNullOrEmpty() && !inputConfig.allLangs.isNullOrEmpty()) {
                    val rowBean = RowBean()
                    // 比如allHeads="xml_name,id,ar,jp,en-rGB,en-rUS"
                    allHeads.forEach {
                        // 比如 en-rGB，会将这一列的相关的保存起来
                        val langValue = cellDataMap[allHeads.indexOf(it)]
                        if (!langValue.isNullOrEmpty()) {
                            // langs["en-rGB"] = "Auto Focus on Startup"
                            // langs["ja"] = "起動時の自動焦点"
                            // langs["zh-rCN"] = "开机自动对焦"
                            rowBean.langs[it] = langValue
                        }
                    }
                    // keyName(id), isArray(是否为数组), arrayIndex(数组坐标) 等初始化
                    rowBean.getRowAttrValue()
                    // 解析 json 数据
                    progress(rowBean)
                    datas.add(rowBean)
//                    println("EasyExcelFactory.read invoke id:${rowBean.rowAttr?.keyName} size:${rowBean.langs.size}")
                }
            }

            override fun doAfterAllAnalysed(context: AnalysisContext?) {
                println("EasyExcelFactory.read doAfter excel file all Langs size:${inputConfig.allLangs?.size} datas size:${datas.size}")
                complete(datas)
            }
        }).ignoreEmptyRow(true).sheet(sheetIndex).doRead()
        println("=====readRowsBySheetName=====end")
    }

//    fun writeDataBySheetName(excelPath: String, sheetName: String?, exportConfig: ExportConfig, data: List<RowBean>) {
    fun writeDataBySheetName(exportConfig: ExportConfig, data: List<RowBean>) {
        println("writeDataBySheetName")
        val excelPath = exportConfig.excelPath
        val sheetName = exportConfig.projectName
        val file = File(excelPath)
        if (!file.exists()) {
            file.createNewFile()
        }

        //创建sheet
        val writeSheet = WriteSheet()
        writeSheet.sheetName = sheetName
        writeSheet.sheetNo =2

        //创建表头
        val writeTable = WriteTable()
        writeTable.tableNo = 1
        val headData = mutableListOf(
            mutableListOf("字段属性(请勿修改内容)", Constant.FIELD_PROPERTY),
        )
        //
        val langHead = exportConfig.selectLangs?.map {
            val note = Constant.langMap[it] ?: "暂无备注"
            mutableListOf(note, it)
        }!!.toMutableList()
        headData.addAll(langHead)
        writeTable.head = headData

        //填入数据
        val rowData = data.map { row ->
            mutableListOf<String>().apply {
                headData.forEach { lang ->
                    // ar,cs,da,de,en-rGB,cn-rCN等等
                    val langName = lang[1]
                    if (row.langs.containsKey(langName)) {
                        add(row.langs[langName]!!)
                    } else {
                        /*
                         * 比如标题有ar, 某模块的 values-ar 无 字段，导致excel表格排序位置出问题(导致向前移动).
                         * 需要添加空的字符串补齐位置
                         */
                        add("")
                    }
                }
            }
        }.toMutableList()

        EasyExcelFactory
            .write(file)
            .registerWriteHandler(object : SheetWriteHandler {
                override fun afterSheetCreate(
                    writeWorkbookHolder: WriteWorkbookHolder?,
                    writeSheetHolder: WriteSheetHolder?
                ) {
                    //冻结 第1~2行
                    super.afterSheetCreate(writeWorkbookHolder, writeSheetHolder)
                    writeSheetHolder?.sheet?.createFreezePane(0, 2, 0, 2)
                }
            })
            .build()
            .write(rowData, writeSheet, writeTable)
            .finish()
    }

}

val gson = Gson()